package com.qingzhu.component.lock.common.pool;

import com.qingzhu.component.lock.annotation.LockCommonBeanAnnotation;
import com.qingzhu.component.lock.common.config.LockProperties;
import com.qingzhu.component.lock.common.exception.LockExpiredException;
import org.springframework.beans.factory.annotation.Value;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 这是一个自定义的简陋的线程池
 * 目的是为了控制从每次请求的主线程中fork的线程数量
 * @author xiangjz
 * @version 1.0
 * @date 2021/6/10 9:32
 */
@LockCommonBeanAnnotation
public class ForkLockExecutor {

    private Semaphore semaphore;

    public ForkLockExecutor(LockProperties lockProperties) {
        this.semaphore = new Semaphore(lockProperties.getForkTaskQueueSize());
    }

    public void awaitIfFull(long timeout) {
        try {
            if(timeout >= 0) {
                if(!this.semaphore.tryAcquire(timeout, TimeUnit.MILLISECONDS)) {
                    // 超时之后，还是不能获取到整体阈值，直接抛异常，视为中断
                    throw new LockExpiredException("fork thread for business exception, timeout");
                }
            } else {
                this.semaphore.acquire();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void release() {
        this.semaphore.release();
    }
}
